﻿using System.Xml.Linq;

namespace EasyXaf.DynamicForm.Models;

public class Table : Field
{
    public List<Column> Columns { get; }

    public Table(Form form, Element parent)
        : base(form, parent)
    {
        Columns = [];
    }

    public override void WriteXml(XElement element)
    {
        base.WriteXml(element);

        foreach (var column in Columns)
        {
            var columnElement = column.CreateXElement();
            column.WriteXml(columnElement);
            element.Add(columnElement);
        }
    }

    public override void ReadXml(XElement element)
    {
        base.ReadXml(element);

        Columns.Clear();

        foreach (var columnElement in element.Elements())
        {
            var elementName = columnElement.Name.LocalName;
            if (elementName == "column")
            {
                var column = new Column(Form, this);
                column.ReadXml(columnElement);
                Columns.Add(column);
            }
        }
    }

    public override XElement CreateXElement()
    {
        return new XElement("table");
    }
}
